package com.woniuxy.rbac.web.api;

import com.woniuxy.rbac.entity.ResponseResult;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 *
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
@RestControllerAdvice
public class WnExceptionHandler {
    @ExceptionHandler(DataAccessException.class)
    public ResponseResult<Void> handlerException(DataAccessException e) {
        e.printStackTrace();
        return ResponseResult.FAIL;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Void> handler(MethodArgumentNotValidException ex) {
        Map<String, String> msgs = new HashMap<>();
        ex.getFieldErrors().forEach(e -> {
//            System.out.println(e.getField());
//            System.out.println(e.getDefaultMessage());
            msgs.put(e.getField(), e.getDefaultMessage());
        });
        return new ResponseResult(601, "参数无效", msgs);
    }

}
